import { defineStore } from 'pinia';
import { TOKEN_NAME } from '@/config/global';
import { store, usePermissionStore } from '@/store';

import{passwordLogin,getLoginInfo} from '@/api/member'

const InitUserInfo = {
  name:'user',
  roleTxt:'用户',
  roles: [],
};

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem(TOKEN_NAME) || 'main_token', // 默认token不走权限
    userInfo: { ...InitUserInfo },
  }),
  getters: {
    roles: (state) => {
      return state.userInfo?.roles;
    },
  },
  actions: {
    async login(userInfo: Record<string, unknown>) {
   const data= {
        account:userInfo.account as string,
        password:userInfo.password as string,
        verifyCode:userInfo.verifyCode as string
      }
       await passwordLogin(data)
       .then(ret=>{
         this.token=ret.access_token
         localStorage.setItem(TOKEN_NAME,this.token)
          this.getUserInfo()
       })
    },
    async getUserInfo() {
      await getLoginInfo().then(ret=>{
        this.userInfo=ret
      })

      // const res = await mockRemoteUserInfo(this.token);

      // this.userInfo = res;
    },
    async logout() {
      localStorage.removeItem(TOKEN_NAME);
      this.token = '';
      this.userInfo = { ...InitUserInfo };
    },
    async removeToken() {
      this.token = '';
    },
  },
  persist: {
    afterRestore: (ctx) => {
      if (ctx.store.roles && ctx.store.roles.length > 0) {
        const permissionStore = usePermissionStore();
        permissionStore.initRoutes(ctx.store.roles);
      }
    },
  },
});

export function getUserStore() {
  return useUserStore(store);
}
